//
//  TabBar.swift
//  swiftImitationWeibo
//
//  Created by 杨果果 on 16/7/9.
//  Copyright © 2016年 yang. All rights reserved.
//

import UIKit

//代理发送点击事情
protocol TabBarDelegate : NSObjectProtocol{
    func didselectedComposeButton()
}


//自定义TabBar
class TabBar: UITabBar {
    //遵守代理   定义一个代理属性
    
    weak var tabDelegate = TabBarDelegate?()
//定义闭包  发送点击事件 、
    var composeButtonClosure:(()->())?
    
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Selected)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Selected)
        button.sizeToFit()
        return button
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    private func setupUI() {
        addSubview(composeButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //调整子控制器frame
    override func layoutSubviews() {
        super.layoutSubviews()
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        var index = 0
        let itemWidth = width / 5
        for value in subviews {
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                value.width = itemWidth
                value.x = CGFloat(index) * itemWidth
                index++
                if index == 2{
                    index++
                }
            }
        }
 
    }
    
    
    @objc private func composeButtonAction(){
        composeButtonClosure?()
        //调用代理  
        tabDelegate?.didselectedComposeButton()
    }
    
    
    
}
